# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import json

from itemadapter import ItemAdapter


import urllib.request


# class HotRankPicPipeline:
#
#     def process_item(self, item, spider):
#         url = item.get('pic')
#         filename = './rankpic/' + item.get('title') + '.jpg'
#
#         urllib.request.urlretrieve(url=url, filename=filename)
#         return item


# 加载settings文件
from scrapy.utils.project import get_project_settings
from kafka import KafkaProducer
import pymysql


class MysqlPipeline:
    # DB_HOST = 'www.91iedu.com'
    # DB_POST = 3391
    # DB_USER = 'tjpu1904'
    # DB_PASSWORD = 'tjpu1904'
    # DB_NAME = 'tjpu1904'
    # DB_CHARSET = 'utf-8'
    def open_spider(self, spider):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.name = settings['DB_NAME']
        self.charset = settings['DB_CHARSET']

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            db=self.name,
            charset=self.charset
        )

        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):

        sql = 'insert into game_list(ranks,bvid,cid,pic,title,owner,views,danmaku,reply,favorite,coin,share,likes,short_link)' \
              'values ("{}","{}","{}","{}","{}","{}","{}","{}","{}","{}","{}","{}","{}","{}")'.format(
            item['ranks'],item['bvid'],item['cid'],item['pic'],item['title'],item['owner'],item['view'],item['danmaku'],item['reply'],item['favorite'],item['coin'],item['share'],item['like'],item['short_link']
        )
        self.cursor.execute(sql)
        self.conn.commit()

        # 开启后提交到kafka消息队列
        # self.process_item_to_kafka(item)

        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()

    def process_item_to_kafka(self, item):

        self.producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('gbk'),
                                      bootstrap_servers=['master:9092'])

        tmp = {
            'ranks': item["ranks"],
            'bvid': item["bvid"],
            'cid': item["cid"],
            'pic': item["pic"],
            'title': item["title"],
            'owner': item["owner"],
            'view': item["view"],
            'danmaku': item["danmaku"],
            'reply': item["reply"],
            'favorite': item["favorite"],
            'coin': item["coin"],
            'share': item["share"],
            'like': item["like"],
            'short_link': item["short_link"]
        }

        self.producer.send('demo_list', tmp)
        pass